
#ifndef  SEARCHSORT_CPP_H
#define  SEARCHSORT_CPP_H

// 获取对应序号的内存数组值的指针
static void* __internal_dataPointer(int index, size_t dataIdx) {
	if (index == INDEX_BAODAN)
		return orders->data(dataIdx);
	else if (index == INDEX_JIAOGE)
		return deliveryOrders->data(dataIdx);
	else if (index == INDEX_ZHONGLICANG)
		return middleOrders->data(dataIdx);
	else if (index == INDEX_CHENGJIAODAN)
		return contractNotes->data(dataIdx);
	else if (index == INDEX_JG_CHENGJIAODAN || index == INDEX_ZLC_CHENGJIAODAN)
		return deliveryContractNotes->data(dataIdx);
	else if (index == INDEX_GONGGAO)
		return notices->data(dataIdx);
	return NULL;
}

// 二分查找、并更新索引
// 参数:index   引用内存数组序号
// 参数:size    索引当前大小
// 参数:idx     索引
// 参数:dataIdx 待更新索引数据的数组序号
// 参数:data    待更新索引数据
// 参数:field   索引对应排序字段
// 参数:mode    索引处理类型（使用MODE_NONE/INSERT/DELETE宏）
int _binarysearch(int index, int size, int* idx, int dataIdx, void* data, int field, char mode) {
	if (size == 0) {
		if (mode == MODE_INSERT)
			idx[0] = dataIdx;
		return NOT_FOUND; // 如果当前大小为空肯定无匹配
	}
	int low = 0; // 二分查找低值
	int high = size - 1; // 二分查找高值
	int middle = 0;
	int flag = NOT_FOUND_LEFT;
	void* _data;
	if (data == NULL && mode != MODE_INSERT)
		data = __internal_dataPointer(index, dataIdx);
	while (low <= high) {
		middle = (low + high) / 2;
		_data = __internal_dataPointer(index, idx[middle]);
		if (_compare_lt[index](_data, data, field)) {
			low = middle + 1;
			flag = NOT_FOUND_RIGHT;
		}
		else if (_compare_gt[index](_data, data, field)) {
			high = middle - 1;
			flag = NOT_FOUND_LEFT;
		}
		else {
			if (mode == MODE_DELETE) {
				for (int i = middle; i < size - 1; i++)
					idx[i] = idx[i + 1];
			}
			return middle;
		}
	}
	if (mode == MODE_INSERT) {
		if (flag == NOT_FOUND_RIGHT)
			middle++;
		// 注意这里插入，必须倒序更新、后面数据赋成前面值
		for (int i = size; i > middle; i--)
			idx[i] = idx[i - 1];
		idx[middle] = dataIdx;
	}
	return NOT_FOUND;
}
// 查询列表快速排序整理
static void _quicksort(int index, int* indexs, int left, int right, int field) {
	//此处编写代码实现快速排序
	int i, j, middle, temp;
	if (left < right) {
		i = left;
		j = right;
		middle = indexs[(left + right) / 2];
		//以中间元素为轴
		while (true) {
			while (i <= right && _compare_lt[index](__internal_dataPointer(index, indexs[i]), __internal_dataPointer(index, middle), field))
				i++;
			while (j >= 0 && _compare_gt[index](__internal_dataPointer(index, indexs[j]), __internal_dataPointer(index, middle), field))

				j--;
			if (i >= j) //相遇则跳出
				break;
			else {
				temp = indexs[i];
				indexs[i] = indexs[j];
				indexs[j] = temp;
			}
		}
		_quicksort(index, indexs, left, i - 1, field); //对左半部分进行快排
		_quicksort(index, indexs, j + 1, right, field); //对右半部分进行快排
	}
}


#endif   /* SEARCHSORT_CPP_H */
